package com.app.internationaltravel.service.impl;

import com.app.internationaltravel.dao.OssLogDao;
import com.app.internationaltravel.dao.UserDao;
import com.app.internationaltravel.entity.OssLog;
import com.app.internationaltravel.service.intf.OssLogService;
import com.app.internationaltravel.util.AliOssUtil;
import com.app.internationaltravel.util.DateUtil;
import com.app.internationaltravel.util.FileUtil;
import com.app.internationaltravel.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

/**
 * @author 刘豆豆
 * @date 2022/12/13
 */
@Service
public class OssLogServiceImpl implements OssLogService {

  @Resource
  private OssLogDao dao;
  @Override
  public R uploadImg(MultipartFile file) {
    //1.验证
    if (!file.isEmpty()){
      try {
        //2.获取文件内容
        byte[] data = file.getBytes();
        //3.获取上传文件名，保持长度，名称为一
        String name = FileUtil.rename(file.getOriginalFilename());
        Date date = DateUtil.getYear(3);
        //4.上传文件内容到OSS
        String url = AliOssUtil.upload(data,name,date);
        //5.验证是否上传成功
        if (StringUtils.hasLength(url)){
          //6.记录到数据库
          dao.insert(new OssLog(name,url,1,date));

          //7.返回图片的访问地址
          return R.ok(url);
        }
      } catch (IOException e) {
        e.printStackTrace();
      }

    }
    return R.fail("亲，图片上传失败，请检查图片内容");
  }

  @Override
  public R uploadVideo(MultipartFile file) {
    //1.验证
    if (!file.isEmpty()){
      try {
        //2.获取文件内容
        byte[] data = file.getBytes();
        //3.获取上传文件名，保持长度，名称为一
        String name = FileUtil.rename(file.getOriginalFilename());
        Date date = DateUtil.getYear(3);
        //4.上传文件内容到OSS
        String url = AliOssUtil.upload(data,name,date);
        //5.验证是否上传成功
        if (StringUtils.hasLength(url)){
          //6.记录到数据库
          dao.insert(new OssLog(name,url,2,date));
          //7.返回图片的访问地址
          return R.ok(url);
        }
      } catch (IOException e) {
        e.printStackTrace();
      }

    }
    return R.fail("亲，视频上传失败，请检查视频内容");
  }

  @Override
  public R all() {
    return R.ok(dao.selectList(null));
  }
}
